<template>
  <div class="app-container">
    <!-- 条件查询区域开始 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item :label="$t('procDef.name')" prop="name">
          <el-input
            v-model="queryParams.name"
            :placeholder="$t('procDef.name')"
            @keyup.enter="tableHooks.handleQuery()"
          />
        </el-form-item>
        <el-form-item :label="$t('procDef.key')" prop="key">
          <el-input
            v-model="queryParams.key"
            :placeholder="$t('procDef.key')"
            @keyup.enter="tableHooks.handleQuery()"
          />
        </el-form-item>
        <el-form-item class="search-btn">
          <el-button type="primary" @click="tableHooks.handleQuery()">
            {{ $t("common.search") }}
          </el-button>
          <el-button @click="tableHooks.resetQuery()">{{
            $t("common.reset")
          }}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 条件查询区域结束 -->
    <el-card shadow="never" class="table-container">
      <!-- 按钮开始 -->
      <template #header>
        <!-- 按钮开始 -->
        <el-row justify="space-between" :span="20">
          <el-col :span="12">
            <el-button
              type="primary"
              v-hasPerm="['flow:proc_def:add']"
              @click="handleAdd"
            >
              {{ $t("flow.deploy") }}
            </el-button>
          </el-col>
          <el-col :span="8" align="right">
            <jmash-column-select
              v-model="tableLabel"
              label-name="flow/proc_def"
            />
          </el-col>
        </el-row>
      </template>
      <!-- 按钮结束 -->

      <!-- 表格开始 -->
      <jmash-table
        class="table-top"
        ref="multipleTableRef"
        row-key="id"
        :list-loading="listLoading"
        :data="tableData"
        :table-label="tableLabel"
        :is-selection="false"
      >
        <!-- suspended -->
        <template #suspended="scope">
          <span>
            {{ Dict.suspendBiz.getValue(scope.data.row.suspended.toString()) }}
          </span>
        </template>
        <template #operation="scope">
          <el-button
            type="primary"
            link
            v-hasPerm="['flow:proc_def:view']"
            @click="handleViewDiagram(scope.data.row)"
          >
            {{ $t("flow.viewDiagram") }}
          </el-button>
          <el-button
            type="primary"
            link
            v-hasPerm="['flow:proc_def:delete']"
            @click="handleDelete(scope.data.row)"
          >
            {{ $t("common.delete") }}
          </el-button>
          <el-dropdown class="dropdown-left">
            <span class="el-dropdown-link">
              {{ $t("common.more") }}
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <div v-hasPerm="['flow:proc_def:view']">
                  <el-dropdown-item @click="flowInstance(scope.data.row)">
                    {{ $t("flow.inst") }}
                  </el-dropdown-item>
                </div>
                <div v-hasPerm="['flow:proc_def:update']">
                  <el-dropdown-item @click="handleEdit(scope.data.row)">
                    {{ $t("common.edit") }}
                  </el-dropdown-item>
                </div>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </jmash-table>
    </el-card>
    <!-- 表格结束 -->
    <procdef-edit
      v-if="editDialog.visible"
      v-model="editDialog.visible"
      :title="editDialog.title"
      :entity-key="entityKey"
      @update="refresh"
      width="900px"
    />
    <procdef-diagram-view
      v-if="viewDialog.visible"
      v-model="viewDialog.visible"
      :title="viewDialog.title"
      :entity-key="entityKey"
      width="900px"
    />
  </div>
</template>
<script setup lang="ts">
import { type Ref, ref, reactive, onActivated } from "vue";
import { type TableColumn, type DialogRef, useTableHooks } from "jmash-core";
import { Dict } from "@/api/flow/dict";

import { useI18n } from "vue-i18n";
const { t } = useI18n();

import { useRouter } from "vue-router";
const router = useRouter();

import type {
  ProcDefReq,
  ProcDefKey,
  FlowProcDefModel,
} from "@/api/flow/prodef/types";

import { procDefApi } from "@/api/flow/prodef/index";

import procdefEdit from "./edit.vue";

import procdefDiagramView from "./view-diagram.vue";

const queryParams = ref<ProcDefReq>({});

const { tableHooks, multipleTableRef, queryFormRef, listLoading, tableData } =
  useTableHooks(t, procDefApi, queryParams);

//重写GetList满足非翻页的场景.
tableHooks.getList = function () {
  // 设置加载状态为true
  this.listLoading.value = true;
  // 调用api的list方法，并传入queryData参数
  procDefApi
    .findList(this.queryData.value)
    .then(({ data }) => {
      // 检查返回的数据是否有效
      if (!data || typeof data !== "object") {
        console.error("Invalid data received.");
        this.listLoading.value = false;
        return;
      }
      // 将返回的数据中的results赋值给tableData
      this.tableData.value = data.results;
      // 设置加载状态为false
      this.listLoading.value = false;
      // 将返回的数据中的totalSize赋值给total
      this.total.value = data.results.length;
    })
    .catch((error) => {
      // 捕获错误并打印错误信息
      console.error("An error occurred:", error);
      this.listLoading.value = false;
    });
};

let tableLabel: Ref<TableColumn[]> = ref([
  {
    label: "procDef.id",
    prop: "id",
    width: "240",
    sortable: true,
    isColumn: true,
  },
  {
    label: "procDef.key",
    prop: "key",
    width: "200",
    sortable: true,
    isColumn: true,
  },
  {
    label: "procDef.name",
    prop: "name",
    width: "200",
    sortable: true,
    isColumn: true,
  },
  {
    label: "procDef.tenantId",
    prop: "tenantId",
    width: "100",
    isColumn: true,
  },
  {
    label: "procDef.version",
    prop: "version",
    width: "80",
    sortable: true,
    isColumn: true,
  },
  {
    label: "procDef.suspended",
    prop: "suspended",
    width: "150",
    slotName: "suspended",
    columnType: "slot",
    sortable: true,
    isColumn: true,
  },
  {
    label: "procDef.description",
    prop: "description",
    isColumn: true,
  },
  {
    label: "common.operate",
    width: "220",
    slotName: "operation",
    columnType: "slot",
    fixed: "right",
    isColumn: true,
  },
]);

//编辑Dialog
const editDialog = ref({
  title: t("common.edit"),
  visible: false,
} as DialogRef);

//查看Dialog
const viewDialog = ref({
  title: t("flow.viewDiagram"),
  visible: false,
} as DialogRef);

let entityKey = reactive<ProcDefKey>({});

// 新增
function handleAdd() {
  entityKey = reactive<ProcDefKey>({});
  editDialog.value.title = t("flow.deploy");
  editDialog.value.visible = true;
}

// 查看流程图
function handleViewDiagram(row: FlowProcDefModel) {
  entityKey.procDefId = row.id;
  viewDialog.value.visible = true;
}

// 删除部署
function handleDelete(row: FlowProcDefModel) {
  // 弹出一个确认框，询问用户是否确定删除记录
  ElMessageBox.confirm(t("common.confirmDelete"), t("common.delete"), {
    // 取消按钮的文本
    cancelButtonText: t("common.cancel"),
    // 确认按钮的文本
    confirmButtonText: t("common.confirm"),
    // 确认框的类型为警告
    type: "warning",
    // 当用户点击确认按钮时，执行删除操作
  })
    .then(() => {
      // 调用 api 的 del 方法删除记录，并传入 id 作为参数
      procDefApi.deleteDeployment(row.deploymentId).then((response: any) => {
        // 如果响应的状态码为 200，表示删除成功
        if (response.status === 200) {
          // 显示删除成功的消息
          ElMessage({
            message: t("common.deleteSuccess"),
            type: "success",
          });
          // 调用 getList() 方法查询数据
          tableHooks.getList();
        }
      });
      // 当用户点击取消按钮或取消框时，执行以下代码块
    })
    .catch((error: any) => {
      // 处理错误，并给用户反馈
      // 在开发环境中可以保留，但在生产环境中应考虑移除或替换为更安全的日志记录方式
      console.error("Deletion failed:", error);
    });
}

//流程实例
function flowInstance(row: FlowProcDefModel) {
  router.push({
    path: "/flow/monitor",
    query: { procDefId: row.id },
  });
}

//流程编辑
function handleEdit(row: FlowProcDefModel) {
  router.push({
    path: "/rawflow/procdef/bpmn",
    query: { procDefId: row.id },
  });
}

/**
 * 从子组件传过来的事件，刷新列表
 *
 * @returns {void}
 */
function refresh(value: boolean) {
  if (value) {
    tableHooks.getList();
  }
}

//查询数据.
onActivated(() => {
  tableHooks.getList();
});
</script>
<style scoped lang="scss">
.el-dropdown-link:focus {
  outline: none !important;
}
</style>
